# Created by yang

from django.forms import ChoiceField
from django.template.library import Library
from django.urls import reverse
from ..service.v1 import site

register = Library()


def xxxxxxxxx(model_form_obj):
    for item in model_form_obj:
        # 主要为了找出,哪些字段后面应该出现添加的超链接,需
        # 1:是ChoiceField的实例
        # 2:改字段对应的model_class已经注册(因为不注册它就不能生成crud默认四个url,此时这个字段的后面不应该出现添加的超链接)
        tpl = {"has_popup": False, "item": item, "url": "dsdsdsd"}
        if isinstance(item.field, ChoiceField) and item.field.queryset.model in site._registry:
            # print(item.field)
            # print(item.field.queryset.model)
            # print(type(item.field.queryset.model))
            model_class = item.field.queryset.model

            url = reverse(
                "{0}:{1}_{2}_add".format(site.namespace, model_class._meta.app_label, model_class._meta.model_name))
            # item.auto_id指的是当前字段在html显示的id,当打开添加页面添加完成后需要将新添加的对象和该id一起回传,
            # 需要将该对象添加到id对应的字段选择中(新建option加入)
            url = "{}?popup={}".format(url,item.auto_id)
            print(url)
            tpl["has_popup"] = True
            tpl["url"] = url
        yield tpl


@register.inclusion_tag('niubin/change_form.html')
def show_form(model_form_obj):
    return {"form": xxxxxxxxx(model_form_obj)}
